package com.example.performance.jmh.demo;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import org.openjdk.jmh.runner.options.TimeValue;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;

/**
 * @author zpMeng
 * @since 9/18/2024
 */
@BenchmarkMode(Mode.Throughput)
@Warmup(iterations = 3, time = 1)
@Measurement(iterations = 4, time = 2)
@Threads(10)
@Fork(1)
@OutputTimeUnit(TimeUnit.SECONDS)
public class SnowflakeTest {
    private static final Snowflake[] SNOWFLAKES = IntStream.rangeClosed(1, 8)
            .mapToObj(Snowflake::create)
            .toArray(Snowflake[]::new);
    private static final AtomicLong ATOMIC_LONG = new AtomicLong(0);

    @Benchmark
    public long getId() {
        return SNOWFLAKES[(int) (ATOMIC_LONG.incrementAndGet() & (1 << 3) - 1)].nextId();
    }

    public static void main(String[] args) throws RunnerException {
        useAnnotation();
        //useBuilder();
    }

    private static void useAnnotation() throws RunnerException {
        Options options = new OptionsBuilder().include(SnowflakeTest.class.getSimpleName())
                .build();
        new Runner(options).run();
    }

    private static void useBuilder() throws RunnerException {
        Options options = new OptionsBuilder().include(SnowflakeTest.class.getSimpleName())
                .forks(1)
                .measurementIterations(3)
                .measurementTime(TimeValue.seconds(1))
                .warmupIterations(3)
                .warmupTime(TimeValue.seconds(1))
                .build();
        new Runner(options).run();
    }
}
